package com.example.boot3.controller;

import com.example.boot3.model.User;
import com.example.boot3.service.JwtTokenService;
import com.example.boot3.service.UserService;
import com.example.boot3.util.JsonData;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 邹成明
 */

@CrossOrigin(origins =  "*")
@RestController
//@RequestMapping("/api")
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    JwtTokenService jwtTokenService;

    @PostMapping("login")
    public JsonData login(HttpServletRequest request, @RequestBody User user) {
        //1、将页面提交的密码password进行md5加密处理
        System.out.println("user_id"+ user.getUser_id());
        System.out.println("password"+DigestUtils.md5DigestAsHex("123456".getBytes()));

        String md5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        User loginUser=userService.findUser(user.getUser_id());

        if(loginUser==null){
            return JsonData.buildError("用户不存在");
        }
        else {
            if(loginUser.getPassword().equals(md5Password)){
                /** 用id或name都行，除登录、个人信息外，后续功能不需要用到id */
                String token = jwtTokenService.generateToken(loginUser.getUser_id().toString());
                HashMap<String,String> res = new HashMap<>();
                res.put("user_id", String.valueOf(loginUser.getUser_id()));
                res.put("user_name",loginUser.getUser_name());
                res.put("avatar",loginUser.getAvatar());
                res.put("type", String.valueOf(loginUser.getType()));
                res.put("token",token);
                return JsonData.buildSuccess(res);
            }
            else{
                return JsonData.buildError("密码错误");
            }
        }

    }
}
